<?php

namespace App\Http\Controllers;

use App\Events\OrderPaid;
use App\Exceptions\InvalidRequestException;
use App\Models\Installment;
use Carbon\Carbon;
use Illuminate\Http\Request;

class InstallmentsController extends Controller
{
    public function index(Request $request)
    {
        $installments = Installment::query()
            ->where('user_id', $request->user()->id)
            ->paginate(10);
        return view('installments.index', ['installments'=> $installments]);
    }

    public function show(Installment $installment)
    {
        $items = $installment->items()->orderBy('sequence')->get();
        return view('installments.show', [
            'installment'=> $installment,
            'items'=> $items,
            'nextItem'=> $items->where('paid_at', null)->first()
        ]);
    }

    public function payByAlipay(Installment $installment)
    {
        if ($installment->order->closed) {
            throw new InvalidRequestException('对应的商品订单已被关闭');
        }
        if (!$nextItem = $installment->items()->whereNull('paid_at')->orderBy('sequence')->first()) {
            throw new InvalidRequestException('该分期订单已结清');
        }
        dd($nextItem);
        return app('alipay')->web([
            // 支付订单号使用分期流水号+还款计划编号
            'out_trade_no' => $installment->no.'_'.$nextItem->sequence,
            'total_amount' => $nextItem->total,
            'subject'      => '支付 Laravel Shop 的分期订单：'.$installment->no,
            // 这里的 notify_url 和 return_url 可以覆盖掉在 AppServiceProvider 设置的回调地址
            'notify_url'   => route('installments.alipay.notify'),
            'return_url'   => route('installments.alipay.return')
        ]);
    }

    public function alipayReturn()
    {
        try{
            app('alipay')->verify();
        } catch (\Exception $e) {
            return view('pages.error', ['msg' => '数据不正确']);
        }
        return view('pages.success', ['msg' => '付款成功']);
    }

    public function alipayNotify()
    {
        $data = app('alipay')->verify();

        list($no, $sequence) = explode('_', $data->out_trade_no);
        if (!$installment = Installment::where('no', $no)->first()) {
            return 'fail';
        }
        if (!$item = $installment->items()->where('sequence', $sequence)->first()) {
            return 'fail';
        }
        // 如果这个还款计划的支付状态是已支付，则告知支付宝此订单已完成，并不再执行后续逻辑
        if ($item->paid_at) {
            return app('alipay')->success();
        }
        // 更新对应的还款计划
        $item->update([
            'paid_at'        => Carbon::now(), // 支付时间
            'payment_method' => 'alipay', // 支付方式
            'payment_no'     => $data->trade_no, // 支付宝订单号
        ]);
        // 如果这是第一笔还款
        if ($item->sequence === 0) {
            $installment->update(['status'=> Installment::STATUS_PENDING]);
            //将订单改为已支付
            $installment->order->update([
                'paid_at'        => Carbon::now(),
                'payment_method' => 'installment', // 支付方式为分期付款
                'payment_no'     => $no, // 支付订单号为分期付款的流水号
            ]);
            event(new OrderPaid($installment->order));
        }
        // 如果这是最后一笔还款
        if ($item->sequence === $installment - 1) {
            $installment->update(['status'=> Installment::STATUS_FINISHED]);
        }
        return app('alipay')->success();
    }
}
